from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from app.crud.testCrud import (
    get_test, get_tests, create_test, update_test, delete_test
)
from app.schemas.testSchema import Test, TestCreate
from app.database import get_db

router = APIRouter(prefix="/api/v1", tags=["Test"])

@router.post("/tests/", response_model=Test)
async def create_test_endpoint(
    test: TestCreate,
    db: AsyncSession = Depends(get_db)
):
    """创建新的Test记录"""
    return await create_test(db, test=test)

@router.get("/tests/", response_model=List[Test])
async def read_tests(
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db)
):
    """获取Test列表（分页）"""
    tests = await get_tests(db, skip=skip, limit=limit)
    return tests

@router.get("/tests/{test_id}", response_model=Test)
async def read_test(
    test_id: int,
    db: AsyncSession = Depends(get_db)
):
    """根据ID获取单个Test记录"""
    db_test = await get_test(db, test_id=test_id)
    if db_test is None:
        raise HTTPException(status_code=404, detail="Test not found")
    return db_test

@router.put("/tests/{test_id}", response_model=Test)
async def update_test_endpoint(
    test_id: int,
    test: TestCreate,
    db: AsyncSession = Depends(get_db)
):
    """更新Test记录"""
    db_test = await update_test(db, test_id=test_id, test=test)
    if db_test is None:
        raise HTTPException(status_code=404, detail="Test not found")
    return db_test

@router.delete("/tests/{test_id}", response_model=Test)
async def delete_test_endpoint(
    test_id: int,
    db: AsyncSession = Depends(get_db)
):
    """删除Test记录"""
    db_test = await delete_test(db, test_id=test_id)
    if db_test is None:
        raise HTTPException(status_code=404, detail="Test not found")
    return db_test